/**
 * @project heima-leadnews
 * @author MECHREVO
 * @date 2024/1/20 16:42:51
 * @version 1.0
 */
package com.heima.article.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.Mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.pojo.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class FreemarkerServiceImpl implements FreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Override
    public void builpage(ArticleDto articleDto) {
        try {
            String content = articleDto.getContent();
            Map<String,Object>dataMap=new HashMap<>();
            dataMap.put("content", JSONArray.parseArray(content));
            Template template = configuration.getTemplate("article.ftl");
            //3.合成完整页面，并将合成后的页面数据用StringWriter暂存
            StringWriter stringWriter = new StringWriter();
            template.process(dataMap,stringWriter);
            //将stringwriter中数据传入到minIO
            ByteArrayInputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
            String path = fileStorageService.uploadHtmlFile("", String.valueOf(articleDto.getId()), is);
            //5.将minIO返回的url回填到字段上
            ApArticle article = new ApArticle();
            article.setId(articleDto.getId());
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
